package com.zmj.dubboannotation.consumermobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tobato.fastdfs.domain.MataData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.zmj.commoncore.constant.RedisConstant;
import com.zmj.commoncore.utils.FileImgUtil;
import com.zmj.commoncore.utils.MemberIdUtil;
import com.zmj.commoncore.utils.UUIDUtil;
import com.zmj.dubboannotation.consumermobile.redis.UserKey;
import com.zmj.dubboannotation.consumermobile.utils.QiniuUtil;
import com.zmj.dubboannotation.serviceapi.api.MemberCouponService;
import com.zmj.dubboannotation.serviceapi.api.MemberService;
import com.zmj.dubboannotation.serviceapi.api.RedisService;
import com.zmj.dubboannotation.serviceapi.enums.ResultEnum;
import com.zmj.dubboannotation.serviceapi.exception.MallAuthorException;
import com.zmj.dubboannotation.serviceapi.model.MallMember;
import com.zmj.dubboannotation.serviceapi.model.MemberCoupon;
import com.zmj.dubboannotation.serviceapi.utils.ResultVOUtil;
import com.zmj.dubboannotation.serviceapi.vo.MemberVO;
import com.zmj.dubboannotation.serviceapi.vo.ResultVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户控制层
 * Created by: meijun
 * Date: 2018/10/16 20:58
 */
@RestController
@Api(value = "MemberController", description = "用户信息接口")
@RequestMapping("/member")
@Slf4j
public class MemberController {

    @Reference
    private MemberService memberService;

    @Reference
    private MemberCouponService memberCouponService;

    @Autowired
    private QiniuUtil qiniuUtil;

    @Reference
    private RedisService redisService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     *  资料修改 头像上传 上传到七牛云
     * @return
     */
    @PostMapping("/upload")
    public ResultVO uploadHeadImg(HttpServletRequest request, @RequestParam(required = false,value = "file") MultipartFile multipartFile, MemberVO memberVO) throws Exception {

           //获取缓存中的memberId,自己只能修改自己的 如果是模拟的则jwt会验证失败
           String memberId = MemberIdUtil.getCookieMemberId(request);
           memberVO.setId(memberId);

           if(!multipartFile.isEmpty()) {
               try {
                   FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
                   if (!FileImgUtil.isImage(inputStream)) {
                       throw new MallAuthorException(ResultEnum.HEAD_NOT_IMG);
                   }
                   String uuid = UUIDUtil.uuid();
                   String path = qiniuUtil.put64image(multipartFile.getBytes(), uuid);
                   memberVO.setHead(path);
               } catch (Exception e) {
                   e.printStackTrace();
                   return ResultVOUtil.error(ResultEnum.MEMBER_UPLOAD_ERROR);
               }
           }

           MallMember member = memberService.selectByPrimaryKey(memberVO.getId());
           //删除之前的
           qiniuUtil.delete(member.getHead());

           memberService.updateByParam(memberVO);

           //更新 redis 用户信息
           String redisUserInfo = objectMapper.writeValueAsString(memberVO);
           redisService.setForTimeM( String.format("%s-%s",UserKey.getById.getPrefix(),memberVO.getId()),redisUserInfo, RedisConstant.TOKEN_EXPIRE);

           return ResultVOUtil.success(redisUserInfo);
    }

    /**
     * 资料修改 头像上传 上传到服务器
     * fastdfs
     *
     * @param request
     * @param multipartFile
     * @param memberVO
     * @return
     * @throws Exception
     */
    @PostMapping("/upload2")
    public ResultVO uploadHeadImg2(HttpServletRequest request, @RequestParam(required = false,value = "file") MultipartFile multipartFile, MemberVO memberVO) throws Exception {

        //获取缓存中的memberId,自己只能修改自己的 如果是模拟的则jwt会验证失败
        String memberId = MemberIdUtil.getCookieMemberId(request);
        memberVO.setId(memberId);

        MallMember member = memberService.selectByPrimaryKey(memberVO.getId());

        if(!multipartFile.isEmpty()) {
            try {
                // 设置文件信息
                Set<MataData> mataData = new HashSet<>();
                mataData.add(new MataData("author", memberId));
                mataData.add(new MataData("description", "用户头像"));

                // 上传   （文件上传可不填文件信息，填入null即可）
                StorePath storePath = fastFileStorageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), FilenameUtils.getExtension(multipartFile.getOriginalFilename()), mataData);
                memberVO.setHead(storePath.getFullPath());

                //删除之前的图片
                try {
                    if (StringUtils.isNotBlank(member.getHead())) {
                        fastFileStorageClient.deleteFile(member.getHead());
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    log.error("[上传头像] 删除旧头像错误,memberId = {} ,imgPath = {}" ,memberVO.getId(),member.getHead() );
                }

            } catch (Exception e) {
                e.printStackTrace();
                return ResultVOUtil.error(ResultEnum.MEMBER_UPLOAD_ERROR);
            }
        }

        memberService.updateByParam(memberVO);

        //更新 redis 用户信息
        String redisUserInfo = objectMapper.writeValueAsString(memberVO);
        redisService.setForTimeM( String.format("%s-%s",UserKey.getById.getPrefix(),member.getId()),redisUserInfo, RedisConstant.TOKEN_EXPIRE);


        return ResultVOUtil.success(redisUserInfo);
    }

    /**
     * 我的优惠券列表
     * @param request
     * @param shopId 店铺ID
     * @param all 是否获取该店铺所有优惠券
     * @return
     */
    @GetMapping("/copon")
    public ResultVO coupon(HttpServletRequest request,Integer shopId,boolean all) {
        String memberId = MemberIdUtil.getCookieMemberId(request);
        MemberCoupon list = memberCouponService.findByShopIdAndMemberId(memberId,shopId);
        return ResultVOUtil.success(list);
    }

    /**
     * 将服务器历史头像删除
     * @param path
     * @return
     */
    public String delete(String path) {
        //   /group1/M00/00/00/rBFNjlwjRsqAV8XtAACSCVhKJL4704.jpg
        // 第一种删除：参数：完整地址
        fastFileStorageClient.deleteFile(path);

        // 第二种删除：参数：组名加文件路径
        // fastFileStorageClient.deleteFile(group,path);

        return "恭喜恭喜，删除成功！";
    }
}
